﻿using Microsoft.Win32;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Forms;

namespace BaiYiMini
{
	public partial class MainWindow : Window
	{
		RegistryKey root = Registry.CurrentUser.CreateSubKey(@"Software\qiselang.cn\BaiYiMini");
		SqlDataAdapter adapter;
		DataTable dt;
		bool exit = false;
		NotifyIcon icon;

		public MainWindow()
		{
			this.Topmost = true;
			InitializeComponent();

			SqlConnection conn = new SqlConnection(new SqlConnectionStringBuilder { DataSource = ".", IntegratedSecurity = true, InitialCatalog = "HAHA" }.ConnectionString);
			adapter = new SqlDataAdapter("SELECT * FROM [Users] ORDER BY Id DESC", conn);
			adapter.UpdateCommand = new SqlCommandBuilder(adapter).GetUpdateCommand();
			adapter.AcceptChangesDuringUpdate = true;

			dt = new DataTable();
			adapter.Fill(dt);

			this.DataContext = dt.DefaultView;
			//list.ItemsSource = dt.DefaultView;

			icon = new NotifyIcon { Icon = Properties.Resources.BaiyiMini, Text = this.Title, Visible = true };

			icon.ContextMenu = new ContextMenu();
			icon.ContextMenu.MenuItems.Add("设置(&S)", delegate { System.Windows.Forms.MessageBox.Show("Test"); });
			icon.ContextMenu.MenuItems.Add("退出(&X)", delegate { icon.Dispose(); exit = true; this.Close(); });
			icon.DoubleClick += delegate { this.Visibility = Visibility.Visible; };
			int[] b = root.GetValue("Bounds", "0,0,525,350").ToString().Split(',').ToArray<int>();
			this.Left = b[0];
			this.Top = b[1];
			this.Hide();
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			adapter.Update(dt);
			root.SetValue("Bounds", this.RestoreBounds.ToString());
			this.Visibility = Visibility.Hidden;
			e.Cancel = !exit;
		}
	}

	public static class Extention
	{
		public static TOut[] ToArray<TOut>(this object[] source)
		{
			System.Collections.Generic.List<TOut> list = new System.Collections.Generic.List<TOut>();
			Type type = typeof(TOut);
			foreach (var item in source) list.Add((TOut)Convert.ChangeType(item, type));
			return list.ToArray();
		}
	}
}
